<?php
/**
 * Created by PhpStorm.
 * User: alex
 * Date: 01.08.14
 * Time: 0:06
 */

include_once "CMS_SQL.php";

class cms_admin extends CMS_SQL{

    public function login($login, $pass){
        $user = $this->db->query("SELECT * FROM `cms_admins` WHERE `name`='".$login."'", PDO::FETCH_OBJ);
        $user = $user->fetch();
        if ( (md5($pass.$user->salt)) == ($user->pass) ){
            return $user->id;
        }else{
            return false;
        }
    }

    public function get_tree(){
        return $this->get_tree_recursion(0, false);
    }

    public function get_tree_recursion($id_parent, $visible_block=true){
        $sql = "SELECT * FROM `vikno_tree` WHERE `id_parent`=".$id_parent;
        if ($visible_block){
            $sql .= " AND `visible`=1 AND `block`=0";
        }
        $sql .= " ORDER BY `position`";
        $tmp = $this->db->query($sql);
        $tmp->setFetchMode(PDO::FETCH_OBJ);
        $result = array();
        if ($tmp){
            while ( $object = $tmp->fetch() ){
                $buf = $this->get_tree_recursion($object->id_tree, $visible_block);
                if ( $buf ){
                    $object->children = $buf;
                }
                $result[] = $object;
            }
            return $result;
        }else{
            return false;
        }
    }

    public function print_tree($array, $level){
        if (sizeof($array)){
            echo '<div class="pom" style="padding-left: '.(10*$level).'px">';
            foreach ($array as $value){
                if (!isset($_COOKIE['e'.$value->id_tree]) || ($_COOKIE['e'.$value->id_tree]==0)){
                    $show = false;
                }else{
                    $show = true;
                }

                if ($value->block) $block = '<li class="ui-state-default ui-corner-all block" title="Блокувати"><span class="ui-icon ui-icon-locked"></span></li>';
                              else $block = '<li class="ui-state-default ui-corner-all unblock" title="Блокувати"><span class="ui-icon ui-icon-unlocked"></span></li>';
                if ($value->visible) $visible = '<li class="ui-state-default ui-corner-all show" title="Приховати"><span class="ui-icon ui-icon-pause"></span></li>';
                                else $visible = '<li class="ui-state-default ui-corner-all hide" title="Зробити видимим"><span class="ui-icon ui-icon-play"></span></li>';

                if (isset($value->children)){
                    $show_children = '<div class="sc ui-icon ui-icon-circlesmall-'.($show?"minus":"plus").'"></div>';
                }else{
                    $show_children = '';
                }
                echo '
                <div class="pom_parent main level'.$level.'">
                    '.$show_children .'
                    <div class="panel" data-element="'.$value->id_tree.'">
                        <ul id="icons" class="ui-widget ui-helper-clearfix">
                            <li class="ui-state-default ui-corner-all edit" title="Редагувати"><span class="ui-icon ui-icon-pencil"></span></li>
                            <li class="ui-state-default ui-corner-all up" title="Вверх"><span class="ui-icon ui-icon-arrowthick-1-n"></span></li>
                            <li class="ui-state-default ui-corner-all down" title="Вниз"><span class="ui-icon ui-icon-arrowthick-1-s"></span></li>
                            <li class="ui-state-default ui-corner-all remove" title="Видалити"><span class="ui-icon ui-icon-close"></span></li>
                            '.$block.$visible.'
                            <li class="ui-state-default ui-corner-all add_next" title="Додати розділ"><span class="ui-icon ui-icon-circlesmall-plus"></span></li>
                            <li class="ui-state-default ui-corner-all add_children" title="Додати підрозділ"><span class="ui-icon ui-icon-squaresmall-plus"></span></li>
                        </ul>
                    </div>
                    <div class="link">
                        <a href="#'.$value->id_tree.'" target="_blank">'.$value->name.'</a> [<a style="font-size:11px;" href="'.$value->link.'">'.$value->link.'</a>]
                    </div>
                </div>';
                if (isset($value->children)){

                    echo '<div class="pom_parent'.($show?'':" hide").'">';

                    $this->print_tree($value->children, $level+1);
                    echo '</div>';
                }
            }
            echo '</div>';
        }
    }

    /**
     * @param $id_tree
     * @param $type_move :
     *  - up
     *  - down
     *  - left (to parent level)
     *  - right (to children level)
     * @return bool|int
     */
    public function move_item($id_tree, $type_move){
        $sql = "SELECT `position`,`id_parent` FROM `vikno_tree` WHERE id_tree = :id_tree";
        $sth = $this->db->prepare($sql, array( PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY ));
        $sth->execute(array(":id_tree"=>$id_tree));
        $sth->setFetchMode(PDO::FETCH_OBJ);
        $current = $sth->fetch();
        $this->count_query++;   // count +1 query

        switch ($type_move){
            case "up":
                $tmp = $this->CMS_query(
                    "SELECT * FROM `vikno_tree` WHERE `id_parent`=:id_parent  AND `position`=:position",
                    array(
                        ':id_parent' => $current->id_parent,
                        ':position'=> $current->position-1
                    )
                );
                $prev = $tmp[0];
                $u1 = $this->CMS_IU(
                    "UPDATE `vikno_tree` SET `position`=:position WHERE `id_tree`=:id_tree",
                    array(
                        ':position' => $prev['position'],
                        ':id_tree' => $id_tree
                    )
                );
                $u2 = $this->CMS_IU(
                    "UPDATE `vikno_tree` SET `position`=:position WHERE `id_tree`=:id_tree",
                    array(
                        ':position' => $current->position,
                        ':id_tree' => $prev['id_tree']
                    )
                );
                return $u1+$u2;
                break;
            case "down":
                $tmp = $this->CMS_query(
                    "SELECT * FROM `vikno_tree` WHERE `id_parent`=:id_parent  AND `position`=:position",
                    array(
                        ':id_parent' => $current->id_parent,
                        ':position'=> $current->position+1
                    )
                );
                $next = $tmp[0];
                $u1 = $this->CMS_IU(
                    "UPDATE `vikno_tree` SET `position`=:position WHERE `id_tree`=:id_tree",
                    array(
                        ':position' => $next['position'],
                        ':id_tree' => $id_tree
                    )
                );
                $u2 = $this->CMS_IU(
                    "UPDATE `vikno_tree` SET `position`=:position WHERE `id_tree`=:id_tree",
                    array(
                        ':position' => $current->position,
                        ':id_tree' => $next['id_tree']
                    )
                );
                return $u1+$u2;
                break;
            case "left":

                break;
            case "right";

                break;
        }
    }

    public static function pre($some){
        echo("<pre>");
        var_dump($some);
        echo("</pre>");
    }

    public function get_parent_id($id){
        $tmp = $this->CMS_query(
            "SELECT `id_parent` FROM `vikno_tree` WHERE `id_tree`=:id_tree",
            array( ':id_tree' => $id )
        );
        if ($tmp) return $tmp['id_parent'];
        return false;
    }

    /**
     * @param $id - id pressed item
     * @param $data - array(
     *      'type'  =>  true|false (children|next),
     *      ...
     *  )
     * @return bool|int
     */
    public function add_new_item($id, $data){
        if ($data['type']){ // new children item (last)

            $current = $this->CMS_query(
                "SELECT MAX(`position`) as m FROM `vikno_tree` WHERE `id_parent`=:id_tree",
                array( ':id_tree' => $id )
            );
            $insert_position = $current[0]['m'];
            if (is_null($insert_position)){ // перший елемент
                $insert_position = 1;
            }else{
                $insert_position++;
            }

            $current = $this->CMS_query(
                "SELECT `level` FROM `vikno_tree` WHERE `id_tree`=:id_tree",
                array( ':id_tree' => $id )
            );
            $level = $current[0]['level'];

            $e = array(
                ':id_parent'=> $id,
                ':name'     => $data['name'],
                ':link'     => $data['link'],
                ':level'    => $level,
                ':position' => $insert_position,
                ':type_content' => $data['type_content'],
                ':visible' => 1,
                ':block'   => 0
            );

        }else{  // new next item
            $current = $this->CMS_query(
                "SELECT `id_parent`,`position`,`level` FROM `vikno_tree` WHERE `id_tree`=:id_tree",
                array( ':id_tree' => $id )
            );
            $this->CMS_IU(
                "UPDATE `vikno_tree` SET `position`=position+1 WHERE `position`>:position",
                array(
                    ':position' => $current['position']
                )
            );
            $e = array(
                ':id_parent'=> $current[0]['id_parent'],
                ':name'     => $data['name'],
                ':link'     => $data['link'],
                ':level'    => $current[0]['level'],
                ':position' => $current[0]['position']+1,
                ':type_content' => $data['type_content'],
                ':visible' => 1,
                ':block'   => 0
            );
        }

        if ($e){
            $flag = $this->CMS_IU(
                "INSERT INTO `vikno_tree` (
                        id_parent,
                        name,
                        link,
                        level,
                        position,
                        type_content,
                        visible,
                        block
                    ) VALUES (
                        :id_parent,
                        :name,
                        :link,
                        :level,
                        :position,
                        :type_content,
                        :visible,
                        :block
                    )",
                $e
            );
            return $flag;
        }
        return false;
    }

    public function remove_item($id){
        $sql_select = 'SELECT `id_tree` FROM `vikno_tree` WHERE `id_parent`=:id_parent';
        $sql_delete = "DELETE FROM `vikno_tree` WHERE `id_tree`=:id_tree";

        $child = $this->CMS_query(
            $sql_select,
            array(
                ':id_parent' => $id
            )
        );

        $flag = $this->CMS_IU(
            $sql_delete,
            array(
                ":id_tree" => $id
            )
        );

        if ($child && count($child)){
            foreach ($child as $temp){
                $flag += $this->remove_item($temp['id_tree']);
            }
        }
        return $flag;
    }

    public function change_block($id){
        $flag = $this->CMS_IU(
            'UPDATE `vikno_tree` SET `block` = IF(`block`=1, 0, 1) WHERE `id_tree`=:id_tree',
            array(
                ":id_tree" => $id
            )
        );
        return $flag;
    }

    public function change_visible($id){
        $flag = $this->CMS_IU(
            'UPDATE `vikno_tree` SET `visible` = IF(`visible`=1, 0, 1) WHERE `id_tree`=:id_tree',
            array(
                ":id_tree" => $id
            )
        );
        return $flag;
    }

} 